package edu.tsinghua.oxy.engineer.job;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * Job执行计划
 *
 * @author sean
 * @date 2021 - 07 - 30 下午1:45
 */
@Component
public class JobScheduler {

    @Resource
    private SchedulerFactoryBean factoryBean;

    /**
     * 执行计划
     */
    @Value("${spider.job.cron}")
    String cron;

    /**
     * 定义一个调度器
     */
    private Scheduler scheduler;

    @PostConstruct
    public void startScheduler() throws Exception{
        //使用调度器工厂获取一个调度器
        scheduler=factoryBean.getScheduler();
        //开启一个任务调度
        startJob();
    }

    /**
     * 编写一个方法 来完成一个任务调度
     */
    public void startJob() throws Exception{
        //将任务加入到调度器中Cron任务触发器
        JobDetail jobDetail = JobBuilder.newJob(UrlJob.class)
                .withIdentity("cronJob", "cron").build();
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                .cronSchedule(cron);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity("cronJobTrigger", "cron")
                .withSchedule(scheduleBuilder).build();
        scheduler.scheduleJob(jobDetail,cronTrigger);
    }
}
